import React, { useState, useEffect } from 'react';
import {
    Button,
    Input,
    Space,
    Table,
    Pagination,
    Modal,
    Select,
    Checkbox,
    Popconfirm,
    Tooltip,
    notification,
} from "antd";

import ResizeableTitle from '../../components/ResizableTitle';
import Header from "../../components/Header";
import City from "../../components/City";
import Menu from "../../components/Menu";

import {fieldGet} from "../../common/common";
import http from "../../request";
import Footer from "../../components/Footer";
import Recycle from "../../components/Recycle";
import Edit from "./edit";
import { store } from '../../store';


const { Option } = Select;
const { Search } = Input;

const Building = () => {
    const field = {city: '=', region: '=', area: '='}
    const formDefault = {city: '', region: '', area: ''}
    const pageDefault = {page: 1, pageSize: 10}
    const [source, setSource] = useState([])

    const column = [
        {
            title: '序号',
            dataIndex: 'id',
            width: 50,
            align: 'center',
        }, {
            title: '定位',
            dataIndex: 'id',
            width: 50,
            align: 'center',
            render: e => <img className="u-btn" src={require('../../assets/icon/icon-30.png').default} alt="" onClick={() => {
                setEstateId(e)
                setEstateTab('4')
                setEstateShow(!0)
            }}/>
        }, {
            title: '楼盘字典',
            dataIndex: 'name',
            width: 150,
            align: 'center',
            render: e => (
                <Tooltip title={e}>
                    <div className="u-line-1" style={{maxWidth: 200}}>{e}</div>
                </Tooltip>
            )
        }, {
            title: '拼音缩写',
            dataIndex: 'pinyin',
            width:100,
            align: 'center',
        }, {
            title: '城区',
            dataIndex: 'region_data',
            align: 'center',
            width:100,
            render: text => text?.name ? text.name : ''
        }, {
            title: '片区',
            dataIndex: 'area_data',
            align: 'center',
            width:100,
            render: text => text?.name ? text.name : ''
        }
        // , {
        //     title: '概要地址',
        //     dataIndex: 'outline_address',
        //     width: 200,
        //     align: 'center',
        //     render: e => (
        //         <Tooltip title={e}>
        //             <div className="u-line-1" style={{maxWidth: 200}}>{e}</div>
        //         </Tooltip>
        //     )
        // }
        , {
            title: '栋数',
            dataIndex: 'building_num',
            width:50,
            align: 'center',
        }
        , {
            title: '选栋',
            align: 'center',
            width:80,
            render: e =>(
                <Checkbox checked={e.is_select_building === "1" ? true : false } is_select_building={e.id} onChange={e=>selectbuilding(e.target)}></Checkbox>
            )
        }
        // , {
        //     title: '地铁/环线',
        //     align: 'center',
        //     render: text => text?.metro ? text.metro + ' ' : '' + text.loop_line
        // }
        , {
            title: '用途',
            dataIndex: 'property_use',
            align: 'center',
            width:100,
        }, {
            title: '类型',
            dataIndex: 'property_type',
            align: 'center',
            width:150,
        }, {
            title: '建房',
            dataIndex: 'years',
            align: 'center',
            width:100,
        }, {
            title: '备注',
            dataIndex: 'memo',
            width: 150,
            align: 'center',
            render: e => (
                <Tooltip title={e}>
                    <div className="u-line-1" style={{maxWidth: 150}}>{e}</div>
                </Tooltip>
            )
        }
        // , {
        //     title: '操作人',
        //     dataIndex: 'user',
        //     align: 'center',
        //     render: e => (
        //         <Tooltip title={e?.nickname??''}>
        //             <div className="u-line-1" style={{maxWidth: 100}}>{e?.nickname??''}</div>
        //         </Tooltip>
        //     )
        // }
        , {
            title: '操作',
            key: 'action',
            width: 100,
            align: 'center',
            render: text => (
                <Space size="middle">
                    <img className="u-btn" src={require('../../assets/icon/icon-16.png').default} alt="" title="转移" onClick={() => transHandle(text)} />
                    <img className="u-btn" src={require('../../assets/icon/icon-12.png').default} alt="" title="编辑" onClick={() => {
                        if(!(system?.lpzd_xg?.value?? 1)) return setbdd(!0)
                        setEstateShow(!0)
                        setEstateId(text.id)
                        setEstateTab('1')
                    }}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() =>(!(system?.lpzd_xg?.value?? 1))?setbdd(!0) : listDel(text.id)}>
                        <img className="u-btn" src={require('../../assets/icon/icon-13.png').default} alt="" title="删除"/>
                    </Popconfirm>
                </Space>
            ),
        }
    ]
    // 城区-树状
    const [menuKeys, setMenuKeys] = useState([])
    // 表格-查询
    const [form, setForm] = useState(formDefault)
    const [keyword, setKeyword] = useState('')
    const [pager, setPager] = useState(pageDefault)
    const [total, setTotal] = useState(0)

    const [merge, setMerge] = useState({show: !1})
    const [mergeForm, setMergeForm] = useState({})
    const [from, setFrom] = useState({name: '', list: []})
    const [to, setTo] = useState({name: '', list: []})
    const [fromList, setFromList] = useState([])
    const [toList, setToList] = useState([])
    const [mergeList, setMergeList] = useState([])

    const [trans, setTrans] = useState({show: !1})
    const [transForm, setTransForm] = useState({})
    const [selected, setSelected] = useState([])

    const [bdd,setbdd] = useState(!1)
    let {system} = {system:undefined}
    if(store.getState().userInfo.group_id !== 3){
        system=store.getState().staff.system
    }
    // 回收站-列
    const backColumns = [
        {
            title: '序号',
            dataIndex: 'id',
        }, {
            title: '定位',
            dataIndex: 'id',
            width: 50,
            render: e => <img className="u-btn" src={require('../../assets/icon/icon-30.png').default} alt="" onClick={() => window.open('/building-edit?id='+e+'&tab=4', '_blank')}/>
        }, {
            title: '楼盘字典',
            dataIndex: 'name',
        }, {
            title: '拼音缩写',
            dataIndex: 'pinyin',
        }, {
            title: '城区',
            dataIndex: 'region_data',
            render: text => text?.name ? text.name : ''
        }, {
            title: '片区',
            dataIndex: 'area_data',
            render: text => text?.name ? text.name : ''
        }
        // , {
        //     title: '概要地址',
        //     dataIndex: 'outline_address',
        //     render: e => (
        //         <Tooltip title={e}>
        //             <div className="u-line-1" style={{maxWidth: 150}}>{e}</div>
        //         </Tooltip>
        //     )
        // }
        , {
            title: '栋数',
            dataIndex: 'building_num',
        }
        // , {
        //     title: '地铁/环线',
        //     render: text => text?.metro ? text.metro + ' ' : '' + text.loop_line
        // }
        , {
            title: '用途',
            dataIndex: 'property_use',
        }, {
            title: '类型',
            dataIndex: 'property_type',
        }, {
            title: '建房',
            dataIndex: 'years',
        }, {
            title: '备注',
            dataIndex: 'memo',
        }
        // , {
        //     title: '操作人',
        //     dataIndex: 'user',
        //     render: e => e?.nickname??''
        // }
    ]

    // 编辑
    const [estateShow, setEstateShow] = useState(!1)
    const [estateId, setEstateId] = useState(0)
    const [estatehouse, setEstatehouse] = useState('')
    const [estateTab, setEstateTab] = useState(1)

    const [change, setchange] = useState(!0)

    const [columns, setcolumns] = useState(column)

    useEffect(() => {
        listGet(form)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [menuKeys, pager])
    useEffect(() => {
        !merge.show && mergeReset()
    }, [merge])
    useEffect(() => {
        !trans.show && transReset()
    }, [trans])
    useEffect(() => {
        !estateShow && setEstateId(0)
    }, [estateShow])
    return (
        <React.Fragment>
            <Header navCur={1}/>
            <div className="Building page u-p-20 u-m-20">
                <div className="part-title">楼盘字典</div>
                <div className="u-flex u-row-between u-m-t-20">
                    <Recycle url='estate' func={listGet} columns={backColumns} change={setchange}/>
                    <div className="u-flex">
                        <Input placeholder="请输入楼盘字典名称或拼音查询" value={keyword} onChange={e => setKeyword(e.target.value)} style={{width: 250}} />
                        <Button size="mini" type="primary" onClick={() => listGet(form)}>
                            <img src={require('../../assets/icon/icon-6.png').default} alt="" />
                        </Button>
                        <div className="u-flex u-m-l-20" onClick={reset}>
                            <img src={require('../../assets/icon/icon-7.png').default} alt="" />
                            <span className="u-m-l-5 u-text-nowrap">清空</span>
                        </div>
                    </div>
                </div>
                <div className="u-m-t-20 u-flex u-col-top">
                    <Menu menuKeys={menuKeys} menuChange={menuChange}/>
                    <Table sticky bordered size="small" scroll={{x: 1280}} rowSelection={{
                        selectedRowKeys: selected,
                        onChange: (key) => {
                            setSelected(key)
                        }
                    }} onRow={e => ({
                        onClick: () => {
                            setEstatehouse(e.name)
                        },
                        onDoubleClick: () => {
                            setEstateShow(!0)
                            setEstateId(e.id)
                            setEstateTab('1')
                        }
                    })} rowKey={e => e.id+','+e.name+','+(e.region_data?.name??'')} components={{
                        header: {
                            cell: ResizeableTitle
                        }
                    }} dataSource={source} columns={columns.map((col, index) => {
                        return {
                            ...col,
                            onHeaderCell: (column) => ({
                                width: column.width,
                                onResize: (e, { size }) => {
                                    setcolumns((columns) => {
                                        const nextColumns = [...columns];
                                        nextColumns[index] = {
                                            ...nextColumns[index],
                                            width: size.width
                                        }
                                        return nextColumns;
                                    })
                                }
                            })
                        }
                    })} pagination={false} style={{width: '100%', maxHeight: 800, overflowY: 'auto'}}/>
                </div>
                <div className="u-flex u-row-between u-m-t-20">
                    <div>
                        <Button type="primary" size="small" onClick={() => {
                            if(!(system?.lpzd_xz?.value?? 1)) return setbdd(!0)
                            setEstateShow(!0)
                            setEstateTab('1')
                        }}>
                            <div className="u-flex">
                                <img src={require('../../assets/icon/icon-18.png').default} alt=""/>
                                <span className="u-m-l-5">新增</span>
                            </div>
                        </Button>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={listDel}>
                            <Button className="u-m-l-20" type="primary" size="small" danger>
                                <div className="u-flex">
                                    <img src={require('../../assets/icon/icon-19.png').default} alt=""/>
                                    <span className="u-m-l-5">删除</span>
                                </div>
                            </Button>
                        </Popconfirm>
                        <Button className="u-m-l-20" type="primary" size="small" ghost onClick={() => setMerge({show: !0})}>
                            <div className="u-flex">
                                <img src={require('../../assets/icon/icon-17.png').default} alt=""/>
                                <span className="u-m-l-5">合并</span>
                            </div>
                        </Button>
                    </div>
                    <Pagination showQuickJumper current={pager.page} pageSize={pager.pageSize} total={total} onChange={(page, pageSize) => setPager({page, pageSize})} />
                </div>
            </div>
            <Footer/>
            <Modal title="合并楼盘字典" width={560} visible={merge.show} onOk={mergeConfirm} onCancel={() => setMerge({show: !1, text: ''})}>
                <div className="Modal">
                    <div className="u-flex">
                        <div className="label">查找</div>
                        <Search value={from.name} onChange={e => mergeChange(setFrom, from, 'name', e.target.value)} onSearch={e => mergeSearch(setFrom, from, e)} placeholder="楼盘" className="u-m-l-10" style={{ width: 200 }} />
                        <div className="label u-m-l-20">再查找</div>
                        <Search value={to.name} onChange={e => mergeChange(setTo, to, 'name', e.target.value)} onSearch={e => mergeSearch(setTo, to, e)} placeholder="楼盘" className="u-m-l-10" style={{ width: 200 }} />
                    </div>
                    <div className="u-flex u-m-t-20">
                        <div className="label">将要</div>
                        <Select value={mergeForm?.estate_1??''} onChange={e => fromSelect(e)} className="u-m-l-10" style={{ width: 200 }}>
                            { from.list.map(e => <Option value={e.id}>{e.name}</Option>) }
                        </Select>
                        <div className="label u-m-l-20">合并到</div>
                        <Select value={mergeForm?.estate_2??''} onChange={e => toSelect(e)} className="u-m-l-10" style={{ width: 200 }}>
                            { to.list.map(e => <Option value={e.id}>{e.name}</Option>) }
                        </Select>
                    </div>
                    <div className="u-flex u-col-bottom u-m-t-20">
                        <div>
                            <div className="label u-text-right">栋座对应关系</div>
                            <div className="u-flex u-m-t-20">
                                <div className="label"><img src={require('../../assets/icon/icon-20.png').default} alt=""/></div>
                                <div className="value u-m-l-10" style={{color: '#41c47b', fontSize: '12px'}}>本操作涉及大量数据，为避免影响日常业务，同时保证数据的一致性，请安排在晚上或者周末进行。</div>
                            </div>
                            <Checkbox checked={mergeForm.is_del} onChange={mergeDel} className="u-m-t-20"><span style={{ color: 'red' }}>合并后删除被合并楼盘字典</span></Checkbox>
                        </div>
                        <div className="u-flex u-col-top merge u-m-l-25">
                            <div className="u-content-color" style={{ width: 285, height: 160, border: '1px solid #eee', overflowY: 'auto' }}>
                                <div className="u-flex u-border-bottom" style={{position: 'sticky', top: 0, zIndex: 10, background: '#fff'}}>
                                    <div className="u-p-5 u-text-center" style={{ width: '40%' }}>栋座</div>
                                    <div className="u-p-5 u-text-center" style={{ width: '20%' }}>对应</div>
                                    <div className="u-p-5 u-text-center" style={{ width: '40%' }}>栋座</div>
                                </div>
                                { fromList.map((e, i) => {
                                    return (
                                        <div className="u-flex u-border-bottom" key={e.id}>
                                            <div className="u-p-5 u-text-center u-line-1" style={{ width: '40%' }}>{e.name}</div>
                                            <div className="u-p-5 u-text-center" style={{ width: '20%' }}></div>
                                            <div className="u-p-5 u-text-center" style={{ width: '40%' }}>
                                                <Select onChange={e => toChange(e, i)} className="u-m-l-10" style={{width: '90%'}}>
                                                    { toList.map(e => <Option value={e.id}>{e.name}</Option>) }
                                                </Select>
                                            </div>
                                        </div>
                                    )
                                }) }
                            </div>
                        </div>
                    </div>
                </div>
            </Modal>
            <Modal title="楼盘字典转城区" okText="开始转换" width={400} visible={trans.show} onOk={transConfirm} onCancel={() => setTrans({show: !1, text: ''})}>
                <div className="Modal">
                    <div className="u-content-color">将楼盘字典【{transForm.name}】从【{transForm.city_name}{transForm.region_name}{transForm.area_name}】转到：</div>
                    <City value={[transForm.city, transForm.region, transForm.area]} onChange={transChange} className="u-m-t-20"/>
                    <div className="u-flex u-m-t-20">
                        <img src={require('../../assets/icon/icon-20.png').default} alt=""/>
                        <div className="value u-m-10" style={{ width: 200, color: '#41c47b', fontSize: '12px' }}>本操作涉及大量数据，为避免影响日常业务，同时保证数据的一致性，请安排在晚上或者周末进行。</div>
                    </div>
                </div>
            </Modal>
            <Modal title="楼盘信息" width={1100} visible={estateShow} footer={false} onCancel={() => setEstateShow(!1)} destroyOnClose>
                <Edit change={setchange} close={setEstateShow} refresh={listGet} id={estateId} house={estatehouse} setId={setEstateId} tab={estateTab} />
            </Modal>
            <Modal title="提示" footer={false} visible={bdd} onCancel={() => setbdd(!1)}>
                <h3>权限不足</h3>
            </Modal>
        </React.Fragment>
    )
    function menuChange(id, city, region, area){
        let newForm = JSON.parse(JSON.stringify(form))
        newForm.city = city
        newForm.region = region
        newForm.area = area
        setForm(newForm)
        setchange(!1)
        listGet()
        setMenuKeys(['city-'+id])
    }
    function listGet(params = {}){
        // console.log(field,'field');
        // console.log(params,'params');
        // console.log('楼盘字典000');
        if(!(system?.lpzd_ck?.value?? 1)) return setbdd(!0)
        if(change && JSON.parse(sessionStorage.getItem('building_list'))){
            const house = JSON.parse(sessionStorage.getItem('building_list'))
            for (const key in house.rows) {
                if (key*1 === pager.page) {
                    setSource(house.rows[key])
                    setTotal(house.total)
                    return
                }
            }
        }
        http('estate.index', {
            ...fieldGet(
                field, 
                params, 
                pager.page,
                pager.pageSize
                ),
            keyword,
        }).then(res => {
            if(res.code === 1){
                const page = pager.page
                if(total && change){
                    let arr = JSON.parse(sessionStorage.getItem('building_list'))
                    arr.rows[page] = []
                    res.data.rows.forEach(i=>arr.rows[page].push(i))
                    sessionStorage.setItem('building_list',JSON.stringify(arr))
                    setchange(!0)
                    setSource(res.data.rows)
                    setTotal(res.data.total)
                    return
                }
                const data = {
                    total:res.data.total,
                    rows:{
                        [page]:res.data.rows
                    }
                }
                sessionStorage.setItem('building_list',JSON.stringify(data))
                setchange(!0)
                setSource(res.data.rows)
                setTotal(res.data.total)
            }
        })
    }
    function listDel(id){
        if(!(system?.lpzd_xz?.value?? 1)) return setbdd(!0)
        let ids = id > 0 ? [id] : selected.map(e => {
            let data = e.split(',')
            return data[0]
        })
        http('estate.del', {ids}).then(res => {
            if(res.code === 1){
                setchange(!1)
                listGet()
            }
        })
    }
    function reset(){
        setSelected([])
        setKeyword('')
        setMenuKeys([])
        setPager(pageDefault)
        setForm(formDefault)
    }

    // 合并-编辑
    function mergeChange(func, form, name, value){
        let newForm = JSON.parse(JSON.stringify(form))
        newForm[name] = value
        func(newForm)
    }
    // 合并-搜索
    function mergeSearch(func, form, value){
        http('estate.index', {
            ...fieldGet(
                {name: 'like'},
                {name: value}
            )
        }).then(res => {
            if(res.code === 1){
                mergeChange(func, form, 'list', res.data.rows)
            }
        })
    }
    // 合并-从-楼盘-选择
    function fromSelect(e){
        let newForm = JSON.parse(JSON.stringify(mergeForm))
        newForm.estate_1 = e
        setMergeForm(newForm)
        http('building.index', {
            ...fieldGet(
                {estate_id: '='},
                {estate_id: e}
            )
        }).then(res => {
            if(res.code === 1){
                setFromList(res.data.rows)
                setMergeList(res.data.rows.map(e => ({old: e.id})))
            }
        })
    }
    // 合并-到-楼盘-选择
    function toSelect(e){
        let newForm = JSON.parse(JSON.stringify(mergeForm))
        newForm.estate_2 = e
        setMergeForm(newForm)
        http('building.index', {
            ...fieldGet(
                {estate_id: '='},
                {estate_id: e}
            )
        }).then(res => {
            if(res.code === 1){
                setToList(res.data.rows)
            }
        })
    }
    // 合并-到-栋座-选择
    function toChange(id, ind){
        let newList = JSON.parse(JSON.stringify(mergeList))
        newList[ind].new = id
        setMergeList(newList)
    }
    // 合并-是否删除
    function mergeDel(e){
        let newForm = JSON.parse(JSON.stringify(mergeForm))
        newForm.is_del = e.target.checked
        setMergeForm(newForm)
    }
    // 合并-提交
    function mergeConfirm(){
        let newForm = JSON.parse(JSON.stringify(mergeForm))
        newForm.building_arr = mergeList
        newForm.is_del = newForm?.is_del?1:0
        http('estate.merge', newForm).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '操作成功'
                })
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            setMerge({show: !1, text: ''})
        })
    }
    // 合并-重置
    function mergeReset(){
        setFrom({name: '', list: []})
        setTo({name: '', list: []})
        setMergeForm({})
        setFromList([])
    }

    // 转区操作
    function transHandle(build){
        setTransForm({
            estate_id: build.id,
            name: build.name,
            city_name: build.city_data?.name??'',
            region_name: build.region_data?.name??'',
            area_name: build.area_data?.name??''
        })
        setTrans({show: !0})
    }
    function transChange(city, region, area){
        let newForm = JSON.parse(JSON.stringify(transForm))
        newForm.city = city
        newForm.region = region
        newForm.area = area
        setTransForm(newForm)
    }
    function transConfirm(){
        http('estate.trans', {
            estate_id: transForm.estate_id,
            city: transForm.city??'',
            region: transForm.region??'',
            area: transForm.area??''
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '操作成功'
                })
                setTrans({show: !1})
                listGet()
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
        })
    }
    function transReset(){
        setTransForm({})
    }

    function selectbuilding(e){
        http('estate.updateXD',{
            id:e.is_select_building,
            is_select_building:e.checked
        }).then(res => {
            console.log(res);
            listGet()
        }).catch(err=>console.log(err))
    }
}

export default Building